package com.salton123.bmob.bargain

import android.app.Application
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.SaveListener
import cn.bmob.v3.update.AppVersion
import com.salton123.app.BaseApplication
import com.salton123.bmob.AppUtils
import com.salton123.log.XLog
import com.salton123.util.RxUtils
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe

/**
 * User: newSalton@outlook.com
 * Date: 2020-01-25 17:13
 * ModifyTime: 17:13
 * Description:
 */
object BargainHelper {
    const val TAG = "BargainHelper"
    fun addItem() {
        var item = BargainItem()
        item.apply {
            bargainLevel = 1
            bargainPrice = 500
            bargainTitle = "京东优惠互砍"
            bargainType = 1
        }
        item.save(object : SaveListener<String>() {
            override fun done(p0: String?, p1: BmobException?) {
                XLog.d(TAG, "[addItem] p0:$p0,p1:$p1")
            }
        })
    }

    fun getRecommendBargainList(): Observable<List<BargainItem>> {
        return Observable.create(ObservableOnSubscribe<List<BargainItem>> { emitter ->
            val query = BmobQuery<BargainItem>()
            query.setLimit(1)
            query.setSkip(0)
            query.findObjects(object : FindListener<BargainItem>() {
                override fun done(list: List<BargainItem>?, e: BmobException?) {
                    if (list != null) {
                        emitter.onNext(list)
                        emitter.onComplete()
                    } else {
                        if (e != null) {
                            emitter.onError(e)
                        } else {
                            emitter.onError(Throwable("list == null"))
                        }
                    }
                }
            })
        }).compose(RxUtils.schedulersTransformer())
    }

}